<template>
  <section>
    <div class="card margin-top">
      <t-table
        row-key="id"
        :data="tableData"
        :columns="props.columns"
        v-model:selectedRowKeys="selected"
        stripe
        hover
      >
        <!-- operation字段固定为操作列 slot  -->
        <template #operation="{ row, rowIndex }: any">
          <slot name="operation" :row="row" :rowIndex="rowIndex"></slot>
        </template>
      </t-table>
    </div>
    <div class="card margin-top">
      <t-pagination
        v-model="tableParams.page"
        v-model:pageSize="tableParams.page_size"
        :total="tableParams.total"
        showJumper
        @page-size-change="onPageSizeChange"
        @current-change="onCurrentChange"
      />
    </div>
  </section>
</template>
<script lang="ts" setup>
import { ref, reactive, onMounted, computed, watch } from 'vue';
import { MessagePlugin } from 'tdesign-vue-next';
interface basicTableProps {
  columns: { [key: string]: any }[]; // 列配置项==> 必传
  selectedRowKeys?: number[];
  initParam?: any; //初始化请求参数 ==> 非必传（默认为{}）
  getList: (data?: any) => Promise<any>; // 获取列表 api ==> 必传
  appId?: number | string;
}

const props = withDefaults(defineProps<basicTableProps>(), {
  initParam: {},
});

watch(
  () => props.initParam,
  () => {
    Object.assign(tableParams.params, props.initParam);
    for (let key in tableParams.params) {
      if (tableParams.params[key] === '') delete tableParams.params[key];
    }
    tableParams.page = 1;
    getTableData();
  },
  { deep: true },
);

const emit = defineEmits(['update:selectedRowKeys']);
const selected = computed({
  get() {
    return props.selectedRowKeys;
  },
  set(value) {
    emit('update:selectedRowKeys', value);
  },
});
// 接口参数
const tableParams = reactive({
  page: 1,
  page_size: 10,
  total: 0,
  app_id: props.appId,
  params: {
    ...props.initParam,
  },
});
let tableData = ref([]);
onMounted(() => {
  getTableData();
});
const getTableData = () => {
  props.getList(tableParams).then(res => {
    if (res.data.code == 0) {
      const { lists, total } = res.data.data;
      tableData.value = lists;
      tableParams.total = total;
    } else {
      MessagePlugin.error(res.data.msg);
    }
  });
};
const onPageSizeChange = (size: number) => {
  tableParams.page = 1;
  tableParams.page_size = size;
  getTableData();
};

const onCurrentChange = (index: number) => {
  tableParams.page = index;
  getTableData();
};

defineExpose({ getTableData });
</script>
